package com.techsoul.common.core.exception;

import com.techsoul.common.core.enums.HttpStatusEnum;
import com.techsoul.common.core.util.MessageUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import lombok.Data;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 基础异常
 *
 * @author liuen
 */
@Data
public class BaseException extends RuntimeException {

    /**
     * 错误码
     */
    private Integer code;

    /**
     * 错误消息
     */
    private String msg;

    /**
     * 错误消息参数
     */
    private Object[] msgArgs;

    /**
     * 异常堆栈信息
     */
    private String stackInfo;

    public BaseException(String msg) {
        this(HttpStatusEnum.ERROR.getCode(), msg, null, null);
    }

    public BaseException(Throwable cause) {
        super(cause);
    }

    public BaseException() {
        this(null, null, null, null);
    }

    public BaseException(HttpStatusEnum httpStatusEnum, String msg, Object[] msgArgs) {
        this(httpStatusEnum.getCode(), msg, msgArgs, null);
    }

    public BaseException(String msg, Object[] msgArgs) {
        this(HttpStatusEnum.ERROR.getCode(), msg, msgArgs, null);
    }

    public BaseException(Integer code, String msg, Object[] msgArgs) {
        this(code, msg, msgArgs, null);
    }

    public BaseException(Integer code, String msg, Object[] msgArgs, String stackInfo) {
        this.code = code;
        this.msg = msg;
        this.msgArgs = msgArgs;
        this.stackInfo = stackInfo;
        // 封装异常堆栈信息
        StringWriter sw = new StringWriter();
        this.printStackTrace(new PrintWriter(sw, true));
        this.stackInfo = sw.toString();
    }

    @Override
    public String getMessage() {
        String message = null;
        if (!StringUtils.isEmpty(msg)) {
            if (msgArgs != null) {
                message = MessageUtils.message(msg, msgArgs);
            } else {
                message = msg;
            }
        }
        return message;
    }

}
